<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /* 写法Ⅱ：和递归类似，都是先终止条件，在if判断中添加节点 */
            var pathSum = function (root, targetSum) {
                const result = []
                function preOrder(cur, path, sum) {
                    if (!cur.left && !cur.right && sum == targetSum) {
                        return result.push([...path])
                    }
                    if (!cur.left && !cur.right) return
                    if (cur.left) {
                        path.push(cur.left.val)
                        preOrder(cur.left, path, sum + cur.left.val)
                        path.pop()
                    }
                    if (cur.right) {
                        path.push(cur.right.val)
                        preOrder(cur.right, path, sum + cur.right.val)
                        path.pop()
                    }
                }
                if (!root) return []
                preOrder(root, [root.val], root.val)
                return result
            }
        </script>
    </body>
</html>
